package com.ruoyi.security.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ruoyi.security.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/oauth")
@Slf4j
public class AuthController implements InitializingBean {

    @Autowired
    private CheckTokenEndpoint checkTokenEndpoint;

//    自定义异常翻译器，针对用户名、密码异常，授权类型不支持的异常进行处理
//    private OAuthServerWebResponseExceptionTranslator translate;

    /**
     * 重写/oauth/check_token这个默认接口，用于校验令牌，返回的数据格式统一
     */
    @RequestMapping(value = "/fjw")
    public R getId(@RequestHeader("token") String token) {
//        HttpHeaders headers = request.getHeaders();
        String  id = getIdByToken(token);

        System.out.println("id: " +id);
        return R.ok(id);
    }
    private String  getIdByToken(String token){
        //创建验证对象
        JWTVerifier jwtVerifier= JWT.require(Algorithm.HMAC256("uaa123")).build();
        DecodedJWT verify=jwtVerifier.verify(token);
        Map<String, Claim> claims = verify.getClaims();
        Claim user_name = claims.get("user_name");
        String info = user_name.asString();

        //找出id
        String s ="userId\":";
        int begin = info.indexOf(s);
        String userId = info.substring(begin +s.length(), info.indexOf(",", begin));
        return userId;
    }


    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
